﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Tron.DataStructures;
using Tron.Helpers;

namespace Tron.Players.Simple
{
    class ReflexAgentPlayer : Player
    {
        public ReflexAgentPlayer(int playerIndex)
            : base(playerIndex) { }

        public override void Update(Percepts percepts, Actions actions)
        {
            // Retrieve the player state for this player.
            IPlayerStatePercepts playerState = percepts.PlayerStates[PlayerIndex];

            bool foundTurnoff = false;

            // Look in ahead and search for a turnoff along the path in the direction that the player is currently going.
            Vector2 nextPosition = playerState.Position + playerState.Direction;
            while (percepts.Board[nextPosition] == -2)
            {
                List<Vector2> possibleDirections = SimplePlayerHelper.PossibleDirectionsFromPosition(
                    percepts, nextPosition);
                possibleDirections.Remove(playerState.Direction);
                if (possibleDirections.Count > 1)
                {
                    foundTurnoff = true;
                    break;
                }
                nextPosition = nextPosition + playerState.Direction;
            }

            if (foundTurnoff)
            {
                // A turnoff has been found.
                // Keep going in the current direction.
                // Note: The player may still be heading into a dead-end,
                // but it will at least make one turn before it crashes...
            }
            else
            {
                // No turnoff has been found.
                // Change direction.

                // Get the list of directions that the agent can go.
                List<Vector2> possibleDirections = SimplePlayerHelper.PossibleDirectionsFromPosition(
                    percepts, playerState.Position);

                // The player is changing direction, so its current direction must be removed from the list.
                possibleDirections.Remove(playerState.Direction);

                // Make sure there is at least one direction remaining...
                if (possibleDirections.Count > 0)
                {
                    // Choose a direction at random from those remaining.
                    int randomIndex = RandomAid.NextIntInRange(0, possibleDirections.Count - 1);
                    actions.MoveDirection = possibleDirections[randomIndex];
                }
                else
                {
                    // The player is doomed.  Nothing can be done.
                }
            }
        }
    }
}
